package com.fish.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fish.common.exception.BusinessException;
import com.fish.common.result.ResultCode;
import com.fish.dao.mapper.DictDataMapper;
import com.fish.model.dto.DictDataDTO;
import com.fish.model.entity.DictData;
import com.fish.model.vo.DictDataVO;
import com.fish.service.DictDataService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import jakarta.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 字典数据服务实现类
 */
@Service
public class DictDataServiceImpl implements DictDataService {

    @Resource
    private DictDataMapper dictDataMapper;

    @Override
    public Page<DictDataVO> getPage(Integer pageNum, Integer pageSize, String dictType, String dictLabel) {
        Page<DictData> page = new Page<>(pageNum, pageSize);
        
        LambdaQueryWrapper<DictData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasText(dictType), DictData::getDictType, dictType)
                .like(StringUtils.hasText(dictLabel), DictData::getDictLabel, dictLabel)
                .orderByAsc(DictData::getDictSort)
                .orderByDesc(DictData::getCreateTime);
        
        Page<DictData> dictDataPage = dictDataMapper.selectPage(page, wrapper);
        
        Page<DictDataVO> voPage = new Page<>();
        BeanUtils.copyProperties(dictDataPage, voPage, "records");
        
        List<DictDataVO> voList = dictDataPage.getRecords().stream().map(dictData -> {
            DictDataVO vo = new DictDataVO();
            BeanUtils.copyProperties(dictData, vo);
            return vo;
        }).collect(Collectors.toList());
        
        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public List<DictDataVO> getByType(String dictType) {
        LambdaQueryWrapper<DictData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DictData::getDictType, dictType)
                .eq(DictData::getStatus, 1)
                .orderByAsc(DictData::getDictSort);
        
        List<DictData> list = dictDataMapper.selectList(wrapper);
        
        return list.stream().map(dictData -> {
            DictDataVO vo = new DictDataVO();
            BeanUtils.copyProperties(dictData, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public DictDataVO getById(Long id) {
        DictData dictData = dictDataMapper.selectById(id);
        if (dictData == null) {
            throw new BusinessException(ResultCode.NOT_FOUND);
        }
        
        DictDataVO vo = new DictDataVO();
        BeanUtils.copyProperties(dictData, vo);
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(DictDataDTO dto) {
        // 检查字典值是否已存在
        LambdaQueryWrapper<DictData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DictData::getDictType, dto.getDictType())
                .eq(DictData::getDictValue, dto.getDictValue());
        Long count = dictDataMapper.selectCount(wrapper);
        if (count > 0) {
            throw new BusinessException(ResultCode.ERROR.getCode(), "该字典类型下的字典值已存在");
        }
        
        DictData dictData = new DictData();
        BeanUtils.copyProperties(dto, dictData);
        dictDataMapper.insert(dictData);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DictDataDTO dto) {
        if (dto.getId() == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "字典数据ID不能为空");
        }
        
        DictData existDictData = dictDataMapper.selectById(dto.getId());
        if (existDictData == null) {
            throw new BusinessException(ResultCode.NOT_FOUND);
        }
        
        // 检查字典值是否被其他记录使用
        LambdaQueryWrapper<DictData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DictData::getDictType, dto.getDictType())
                .eq(DictData::getDictValue, dto.getDictValue())
                .ne(DictData::getId, dto.getId());
        Long count = dictDataMapper.selectCount(wrapper);
        if (count > 0) {
            throw new BusinessException(ResultCode.ERROR.getCode(), "该字典类型下的字典值已存在");
        }
        
        DictData dictData = new DictData();
        BeanUtils.copyProperties(dto, dictData);
        dictDataMapper.updateById(dictData);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        DictData dictData = dictDataMapper.selectById(id);
        if (dictData == null) {
            throw new BusinessException(ResultCode.NOT_FOUND);
        }
        
        dictDataMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException(ResultCode.PARAM_ERROR.getCode(), "删除的ID列表不能为空");
        }
        
        dictDataMapper.deleteBatchIds(ids);
    }
}